package com.javaear.beangenerator.processor;

import com.javaear.beangenerator.Beaner;
import com.javaear.beangenerator.Context;
import com.javaear.beangenerator.Fielder;
import com.javaear.beangenerator.support.jdbc.mysql.MysqlStandardTypeDef;
import com.javaear.beangenerator.tools.Assert;
import com.javaear.beangenerator.tools.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Mysql processor
 *
 * @author aooer
 */
public class MysqlReverseProcessor extends AbstractProcessor {

    /**
     * show field sql
     */
    private static final String SHOW_FIELD_MYSQL = "show full fields from %s";

    /**
     * mysql connection
     */
    private Connection conn;

    /**
     * mysql tableName
     */
    private String tableName;

    public void init(Context context) {
        if (conn == null)
            try {
                Assert.notNull(conn = DriverManager.getConnection(context.getString("mysql_url"), context.getString("mysql_user"), context.getString("mysql_password")));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        Assert.notNull(tableName = context.getString("mysql_tableName"));
    }

    public Beaner process() {
        try {
            PreparedStatement ps = conn.prepareStatement(String.format(SHOW_FIELD_MYSQL, tableName));
            ResultSet rs = ps.executeQuery();
            List<Fielder> fieldList = new ArrayList<Fielder>();
            while (rs.next())
                fieldList.add(new Fielder(StringUtils.camelCaseUnderline(rs.getString(1)), MysqlStandardTypeDef.getJavaTypeName(rs.getString(2))));
            rs.close();
            ps.close();
            return new Beaner(tableName, fieldList);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
